package net.mingsoft.document.util;

import net.mingsoft.document.action.r.PermissionResponse;
import net.mingsoft.document.enums.DFileType;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author gengfa
 * @date 22/01/27
 */
public class PermissionUtil {

    private PermissionUtil() {}

    public static final List<String> PERMISSIONS = Arrays.asList("01,02,03,04,05,06".split(","));
    public static final List<String> NAMES = Arrays.asList("授权管理,查看日志,创建文件/文件夹,修改名称/编号,删除,移动/复制".split(","));

    public static final String PERM_READ_LOG = "02";
    public static final String PERM_CREATE_FILE = "03";

    public static final String PERM_NON_EXISTS = "-";
    public static final String PERM_ENABLED = "1";
    public static final String PERM_DISABLED = "0";

    public static final char PERM_ENABLED_CHAR = "1".charAt(0);

    public static final String NO_EXT_PERM = "000000";
    public static final String ALL_EXT_PERM_DOC = "11-111";
    public static final String ALL_EXT_PERM_DIR = "1-1111";

    public static final Map<String, String> PERM_MAP = new LinkedHashMap<>();
    public static List<PermissionResponse> DEFAULT_PERM_RESPONSE;
    public static List<PermissionResponse> ALL_PERM_RESPONSE_DOC;
    public static List<PermissionResponse> ALL_PERM_RESPONSE_DIR;

    static {
        PERMISSIONS.forEach(perm -> PERM_MAP.put(perm, NAMES.get(PERMISSIONS.indexOf(perm))));
        DEFAULT_PERM_RESPONSE = resolvePermString(NO_EXT_PERM);
        ALL_PERM_RESPONSE_DOC = resolvePermString(ALL_EXT_PERM_DOC);
        ALL_PERM_RESPONSE_DIR = resolvePermString(ALL_EXT_PERM_DIR);
    }

    public static String genFilePerm(List<String> selected, String fileType) {
        StringBuilder perm = new StringBuilder();

        for (String p : PERMISSIONS) {
            if (p.equals(PERM_CREATE_FILE) && fileType.equals(DFileType.DOC.getType())) {
                perm.append(PERM_NON_EXISTS);
            } else if (p.equals(PERM_READ_LOG) && fileType.equals(DFileType.DIR.getType())) {
                perm.append(PERM_NON_EXISTS);
            } else {
                if (selected.contains(p)) {
                    perm.append(PERM_ENABLED);
                } else {
                    perm.append(PERM_DISABLED);
                }
            }
        }

        return perm.toString();
    }

    public static List<PermissionResponse> resolvePermString(String perm) {
        List<PermissionResponse> responses = new ArrayList<>();

        int i = 0;
        for (Map.Entry<String, String> e : PERM_MAP.entrySet()) {
            responses.add(new PermissionResponse()
                .setName(e.getValue()).setType(e.getKey())
                    .setEnabled(perm.charAt(i) == PERM_ENABLED_CHAR));
            i++;
        }

        return responses;
    }
}
